#pragma once

#include<iostream>
#include<cstring>
#include<functional>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/wait.h>
#include<pthread.h>
#include"Log.hpp"
#include"InetAddr.hpp"
#include"ThreadPool.hpp"

using namespace log_ns;

enum
{
    SOCKET_ERROR=1,
    BIND_ERROR,
    LISTEN_ERROR
};

const static int gport=8080;
const static int gsock=-1;
const static int gblcklog=8;

using task_t=std::function<void()>;

class TcpServer
{
public:
    TcpServer(uint16_t port=gport)
        :_port(port)
        ,_listensockfd(gsock)
        ,_isrunning(false)
    {}

    void InitServer()
    {
        //创建socket
        _listensockfd=socket(AF_INET,SOCK_STREAM,0);
        if(_listensockfd<0)
        {
            LOG(FATAL,"socket create error\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO,"socket create success,sockfd: %d\n",_listensockfd);

        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_port=htons(_port);
        local.sin_addr.s_addr=INADDR_ANY;

        //bind sockfd 和 Socket addr
        if(bind(_listensockfd,(struct sockaddr*)&local,sizeof(local))<0)
        {
            LOG(FATAL,"bind error\n");
            exit(BIND_ERROR);
        }
        LOG(INFO,"bind success\n");

        //因为tcp是面向连接的，tcp需要未来不断地能够做到获取连接
        if(listen(_listensockfd,gblcklog)<0)
        {
            LOG(FATAL,"listen error\n");
            exit(LISTEN_ERROR);
        }

        LOG(INFO,"listen success\n");
    }



    void Loop()
    {
        _isrunning=true;
        while(_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len=sizeof(client);
            int sockfd=accpt(_listensockfd,(struct sockaddr*)&client,&len);
            if(sockfd<0)
            {
                LOG(WARNING,"accept error\n");
                continue;
            }
            InetAddr addr(client);
            LOG(INFO,"get a new link, client info: %s, sockfd is: %d\n",addr.AddrStr().c_str(),sockfd);

            task_t t=std::bind(&TcpServer::Service,this,sockfd,addr);
            ThreadPool<task_t>::GetInstance()->Equeue(t);
        }

        _isrunning=false;
    }


    void Service(int sockfd,InetAddr addr)
    {
        //长服务
        while(true)
        {
            char inbuffer[1024];//当作字符串
            ssize_t n=read(sockfd,inbuffer,sizeof(inbuffer)-1);
            if(n>0)
            {
                inbuffer[n]=0;
                LOG(INFO,"get a message from client %s,message: %s\n",addr.AddrStr.c_str(),inbuffer);

                std::string echo_string="[server echo] #";
                echo_string+=inbuffer;
                write(sockfd,echo_string,echo_string.size());
            }
            else if(n==0)
            {
                LOG(INFO,"client %s quit\n",addr.AddrStr().c_str());
                break;
            }
            else
            {
                LOG(ERROR,"read error: %s\n",addr.AddrStr().c_str());
                break;
            }
        }
        close(sockfd);
    }

    ~TcpServer()
    {}

private:
    uint16_t _port;
    int _listensockfd;
    bool _isrunning;
};